<?php
/**
 *
 * User: chenzheng
 * Date: 2023/4/4
 * Time: 15:37
 */

namespace app\api\library\index\goodsList;

use app\api\model\MallGoods;
use app\api\model\MallUser;

class V
{
    public static function run($param)
    {
        $userId = $param[ 'userId' ];
        $limit  = $param[ 'limit' ];
        $page   = $param[ 'page' ];
        $offset = ($page - 1) * $limit;
        $total  = MallGoods::with('spec')
            ->where([['status', '=', 1]])
            ->count();
        $where  = [
            ['status', '=', 1],
        ];
        if ( !empty($param[ 'keywords' ])) {
            $where[] = ['title', 'like', '%' . $param[ 'keywords' ] . '%'];
        }
        if ($param[ 'sortType' ] == 2) {
            $order = ['discount_price' => 'desc'];
        } elseif ($param[ 'sortType' ] == 3) {
            $order = ['discount_price' => 'asc'];
        } else {
            $order = ['is_top'=>'desc','sort' => 'asc', 'id' => 'desc'];
        }
        $goods = MallGoods::with([
            'spec' => function ($query) {
                $query->where('delete_time', '=', null);
            },
        ])
            ->where($where)
            ->field('id,title,logo,market_price,discount_price,novice_price,virtual_sales,failure_reward,success_reward,collage_num+1 as collage_num,is_novices_exclusive')
            ->order($order)
            ->limit($offset, $limit)
            ->select();
        foreach ($goods as $key => $value) {
            $goods[ $key ][ 'market_price' ]   = getPrice($value[ 'market_price' ]);
            $goods[ $key ][ 'success_reward' ] = getPrice($value[ 'success_reward' ]);
            $goods[ $key ][ 'failure_reward' ] = getPrice($value[ 'failure_reward' ]);
            $goods[ $key ][ 'novice_price' ]   = getPrice($value[ 'novice_price' ]);
            $goods[ $key ][ 'discount_price' ] = getPrice($value[ 'discount_price' ]);
        }
        $isNovice = MallUser::where('id', $userId)->value('is_novice') ?? 0;
        $page     = [
            'total'      => $total,
            'limit'      => $limit,
            'page'       => $page,
            'total_page' => ceil($total / $limit),
        ];
        $res      = [
            'is_novice' => $isNovice,
            'page'      => $page,
            'list'      => $goods,
        ];
        _outPut(200, $res);
    }
}